﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ServiceModel.Syndication;
using System.Xml;
using System.Configuration;
using System.IO;
using Awesomium.Core;
using Awesomium.Windows.Controls;
using System.Text.RegularExpressions;

namespace ParsecClient
{
    /// <summary>
    /// Interaction logic for ReleaseNotes.xaml
    /// </summary>
    public partial class ReleaseNotes : Window
    {
        public ReleaseNotes()
        {
            InitializeComponent();
        }
        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                this.Close();
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //txtAppVersion.Text = string.Format("Version: {0}", MainWindow.AppVersion);
            try
            {
                string url = ConfigurationManager.AppSettings["ReleaseFeedUrl"]; //http://parsec.codeplex.com/project/feeds/rss?ProjectRSSFeed=codeplex%3a%2f%2frelease%2fparsec
                using (XmlReader reader = XmlReader.Create(url))
                {
                    SyndicationFeed feed = SyndicationFeed.Load(reader);
                    //StringBuilder sb = new StringBuilder();
                    //foreach (SyndicationItem item in feed.Items)
                    //{
                    //    sb.Append("<div class='ReleaseItem'>");
                    //    sb.AppendFormat("<div class='ReleaseSubject'>{0}</div>", item.Title.Text);
                    //    sb.AppendFormat("<div class='ReleaseContent'>{0}</div>", item.Summary.Text);
                    //    sb.Append("</div>");
                    //}
                    List<ReleaseFeedItem> items = feed.Items.Select(x => new ReleaseFeedItem(x)).OrderByDescending(x => x.PublishDate).ToList();
                    items = items.GroupBy(x => x.Version).Select(x => x.First()).ToList();
                    Uri uri = new Uri(@"pack://application:,,,/ReleaseNotes.htm", UriKind.Absolute);
                    string s = "";
                    using (StreamReader rdr = new StreamReader(Application.GetResourceStream(uri).Stream))
                    {
                        s = rdr.ReadToEnd();
                    }
                    s = s.Replace("[CONTENT]", string.Join("", items.Select(x => x.GetHtml()).ToArray()));
                    MyWebBrowser.LoadHTML(s);
                }
            }
            catch (Exception ex)
            {
                string errorMessage = "<div class='ErrorHeader'>Error Loading Release Feed: " + ConfigurationManager.AppSettings["ReleaseFeedUrl"] + "</div><div class='ErrorMessage'>" + ex.Message + "</div>";
                Uri uri = new Uri(@"pack://application:,,,/ReleaseNotes.htm", UriKind.Absolute);
                string s = "";
                using (StreamReader reader = new StreamReader(Application.GetResourceStream(uri).Stream))
                {
                    s = reader.ReadToEnd();
                }
                MyWebBrowser.LoadHTML(s.Replace("[CONTENT]", errorMessage));
            }
        }
    }
    public class ReleaseFeedItem
    {
        private const string TitleRegexPattern = @"^([^:]*): (.*) (\([^\)]*\))$";
        private static Regex TitleRegex = new Regex(TitleRegexPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
        public string Version { get; set; }
        public string VersionDateText { get; set; }
        public string FeedItemType { get; set; }
        public DateTime PublishDate { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public ReleaseFeedItem(SyndicationItem item)
        {
            Title = item.Title.Text;
            Content = item.Summary.Text;
            PublishDate = item.PublishDate.DateTime;
            Match m = TitleRegex.Match(item.Title.Text);
            if (m.Success)
            {
                FeedItemType = m.Groups[1].Value;
                Version = m.Groups[2].Value;
                VersionDateText = m.Groups[3].Value;
            }
        }
        public string GetHtml()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<div class='ReleaseItem'>");
            sb.AppendFormat("<div class='ReleaseSubject'>{0} {1}</div>", Version, VersionDateText);
            sb.AppendFormat("<div class='ReleaseContent'>{0}</div>", Content);
            sb.Append("</div>");
            return sb.ToString();
        }
    }
}
